package cn.xueden.system.service.impl;

import cn.xueden.common.result.Result;
import cn.xueden.system.converter.UserConverter;
import cn.xueden.system.mapper.UserMapper;
import cn.xueden.system.model.entity.User;
import cn.xueden.system.model.form.EditUserForm;
import cn.xueden.system.model.form.UserForm;
import cn.xueden.system.model.vo.UserExcelVO;
import cn.xueden.system.model.vo.UserVO;
import cn.xueden.system.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**功能描述：用户服务实现类
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.system.service.impl
 * @version:1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    private final UserConverter userConverter;

    /**
     * 分页获取用户列表数据
     * @param page
     * @param realName
     * @return
     */
    @Override
    @Cacheable(value = "userList",key = "#page.current+'_'+#page.size+'_'+#realName",
            unless = "#result == null || #result.records.isEmpty()")
    public Page<UserVO> pagingUser(Page<UserVO> page, String realName) {
        Page<UserVO> userVOPage = userMapper.pagingUser(page,realName);
        return userVOPage;
    }

    /**
     * 创建用户
     * @param userForm
     * @return
     */
    @Override
    @CacheEvict(value = "userList",allEntries = true)
    public boolean createUser(UserForm userForm) {
        // 设置默认密码
        userForm.setPassword(new BCryptPasswordEncoder().encode("123456"));
        User user = userConverter.fromToEntity(userForm);
        boolean  result =  userMapper.insert(user)>0;
        return result;
    }

    /**
     * 修改用户
     * @param editUserForm
     * @return
     */
    @Override
    @CacheEvict(value = "userList",allEntries = true)
    public boolean updateUser(EditUserForm editUserForm) {
        // 判断ID 是否为空
        if (editUserForm.getId()==null){
            return false;
        }
        User user = userConverter.editUserForm2User(editUserForm);
        boolean result = userMapper.updateById(user)>0;
        return result;
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @Override
    @CacheEvict(value = "userList",allEntries = true)
    public boolean deleteBatchByIds(String ids) {
        // 字符串转数组
        List<Integer> userIds = Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
        Integer row = userMapper.deleteByIds(userIds);
        return row>0;
    }

    /**
     *  单个删除
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = "userList",allEntries = true)
    public boolean deleteById(Long id) {
        boolean result = userMapper.deleteById(id)>0;
        return result;
    }

    /**
     * 导出用户列表
     * @return
     */
    @Override
    public List<UserExcelVO> listForExport() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        List<User> users = baseMapper.selectList(queryWrapper);

        return users.stream().map(user -> {
            UserExcelVO vo = new UserExcelVO();
            BeanUtils.copyProperties(user, vo);
            vo.setStatus(user.getStatus() == 1 ? "正常" : "禁用");
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 判断用户名是否存在
     * @param userName
     * @return
     */
    @Override
    public boolean existsByUserName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        if (userMapper.selectCount(queryWrapper) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 批量保存导入数据
     * @param cachedDataList
     */
    @Override
    @CacheEvict(value = "userList",allEntries = true)
    public void saveBatchImportData(List<User> cachedDataList) {
        baseMapper.insert(cachedDataList);
    }
}
